package com.example.mq2.mqserver.datacenter;

import com.example.mq2.MqApplication;
import com.example.mq2.mqserver.core.Binding;
import com.example.mq2.mqserver.core.Exchange;
import com.example.mq2.mqserver.core.ExchangeType;
import com.example.mq2.mqserver.core.MSGQueue;
import com.example.mq2.mqserver.mapper.MetaMapper;

import java.io.File;
import java.util.List;

public class DataBaseManager {
    private MetaMapper metaMapper;

    public void init() {
        // Mq2Application.context 这个类就是对应的
        //metaMapper = MqApplication.context.getBean(MetaMapper.class);
        if (!checkDBExists()) {
            createTable();
            createDefaultData();
            System.out.println("[DataBaseManager] 数据库初始化完成！");
        } else {
            System.out.println("[DataBaseManager] 数据库已经存在！");
        }
    }

    private boolean checkDBExists() {
        File file = new File("./data/meta.db");
        if (file.exists()) {
            return true;
        }
        return false;
    }

    private void createTable() {
        metaMapper.createExchangeTable();
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
        System.out.println("[DataBaseManage] 创建表完成！");
    }

    public void deleteDB() {
        File file = new File("./data/meta.db");
        boolean ret = file.delete();
        if (ret) System.out.println("[DataBaseManager] 删除数据库文件成功！");
        else System.out.println("[DataBaseManager] 删除数据库文件失败！");

        // 删除数据库文件之后删除目录
        File dataDir = new File("./data");
        dataDir.delete();
        if (ret) System.out.println("[DataBaseManager] 删除数据库目录成功！");
        else System.out.println("[DataBaseManager] 删除数据库目录失败！");
    }
    private void createDefaultData() {
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setExchangeType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        metaMapper.insertExchange(exchange);
        System.out.println("[DataBaseManager] 创建初始数据完成！");
    }

    // 把其他的数据库操作也在此处进行封装一下
    public void insertExchange(Exchange exchange) {
        metaMapper.insertExchange(exchange);
    }

    public List<Exchange> selectAllExchanges() {
      return metaMapper.selectAllExchanges();
    }

    public void deleteExchange(String exchangeName) {
        metaMapper.deleteExchange(exchangeName);
    }

    public void insertQueue(MSGQueue queue) {
        metaMapper.insertQueue(queue);
    }

    public List<MSGQueue> selectAllQueues() {
        return metaMapper.selectAllQueues();
    }

    public void deleteQueue(String queueName) {
        metaMapper.deleteQueue(queueName);
    }

    public void insertBinding(Binding binding) {
        metaMapper.insertBinding(binding);
    }

    public List<Binding> selectAllBindings() {
        return metaMapper.selectAllBindings();
    }

    public void deleteBinding(Binding binding) {
        metaMapper.deleteBinding(binding);
    }
}

